package cc.magicjson.easy.batch.config;

import cc.magicjson.easy.batch.exception.SqlLoadException;
import cc.magicjson.easy.batch.exception.SqlNotFoundException;
import cc.magicjson.easy.batch.template.SqlTemplate;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.SqlProvider;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static java.util.Objects.isNull;

/**
 * SQL提供者，集中管理SQL语句
 */
@Component
public class BatchSqlProvider {
    private final Map<String, String> sqlTemplates = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        // 从配置文件加载SQL
        loadSqlFromFiles();
    }

    private void loadSqlFromFiles() {
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:sql/*.sql");

            for (Resource resource : resources) {
                String content = FileCopyUtils.copyToString(
                    new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)
                );
                parseSqlFile(content);
            }
        } catch (IOException e) {
            throw new SqlLoadException("Failed to load SQL files", e);
        }
    }

    private void parseSqlFile(String content) {
        String[] lines = content.split("\n");
        StringBuilder currentSql = new StringBuilder();
        String currentKey = null;

        for (String line : lines) {
            line = line.trim();
            if (line.startsWith("-- @SqlKey:")) {
                // 保存前一个SQL
                if (currentKey != null) {
                    sqlTemplates.put(currentKey, currentSql.toString().trim());
                }
                // 开始新的SQL
                currentKey = line.substring("-- @SqlKey:".length()).trim();
                currentSql = new StringBuilder();
            } else if (!line.startsWith("--") && !line.isEmpty()) {
                currentSql.append(line).append(" ");
            }
        }

        // 保存最后一个SQL
        if (currentKey != null) {
            sqlTemplates.put(currentKey, currentSql.toString().trim());
        }
    }

    public String getSql(String key) {
        if(!sqlTemplates.containsKey(key)){
            throw new SqlNotFoundException("this key is not defined: " + key);
        }
        String sql = sqlTemplates.get(key);
        if(isNull(sql) || sql.isEmpty()){
            throw new SqlNotFoundException("SQL not found for key: " + key);
        }
        return sql;
    }


    /**
     * 获取SQL模板
     */
    public SqlTemplate getTemplate(String key) {
        String template = getSql(key);
        return new SqlTemplate(template);
    }

    /**
     * 获取处理过的SQL
     */
    public String getSql(String key, Map<String, String> params) {
        return getTemplate(key)
            .setAll(params)
            .render();
    }

}
